package com.edgclub.edg.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.MessReplyAdapter;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.result.TopicMessageData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReplyFragment extends GzBaseFragment implements View.OnClickListener,VolleyListener{

	private static final String TOPIC_TYPE = "topic_type";
	private Activity mActivity;

	private int currPage = 1;
	private int pageSize = 20;
	private XRecyclerView recyclerView;
	private MessReplyAdapter messReplyAdapter;

	private UserPrefUtils userPrefUtils;

	private boolean isFirstLoad = true;
	private List<TopicMessageData.TopicMess> topicMesses = new ArrayList<>();
	private LinearLayout head_view;
	private TextView head_text;


	public static ReplyFragment newInstance(String topic_type) {
		ReplyFragment f = new ReplyFragment();
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		mActivity = this.getActivity();
		return inflater.inflate(R.layout.fragment_reply, container, false);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		userPrefUtils = new UserPrefUtils(getActivity());
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		initData();
	}
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if((isVisibleToUser&&isFirstLoad)||(isVisibleToUser&&null!=userPrefUtils && userPrefUtils.getUser()!=null &&userPrefUtils.getMessNum()>0)){
			isFirstLoad = false;
			currPage = 1;
			getData(currPage);
		};

	}


	private void initView(View view){
		initLoadView(view);
		recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerview);

		LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(layoutManager);


		head_view= (LinearLayout) view.findViewById(R.id.head_view);
		head_text= (TextView) view.findViewById(R.id.head_view_text);
		head_text.setOnClickListener(this);



		recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
			@Override
			public void onRefresh() {
				currPage = 1;
				getData(currPage);
			}

			@Override
			public void onLoadMore() {
				getData(currPage);
			}
		});

	}

	private void initData(){
		messReplyAdapter=new MessReplyAdapter(getActivity());
		messReplyAdapter.setDatas(topicMesses);
		recyclerView.setAdapter(messReplyAdapter);

//		getData(currPage);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.head_view_text:
				currPage=1;
				getData(currPage);
				break;

		}
	}

	public void getData(int page){
		try {
			PostsParam messageParam=new PostsParam();
			if(null==userPrefUtils){
                userPrefUtils = new UserPrefUtils(getActivity());
            }
			messageParam.setUserId(userPrefUtils.getUser().getId()+"");
			messageParam.setPage(page+"");
			messageParam.setPageSize("20");
			new TopicApi(getActivity()).replyMyPost(messageParam,this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onStart(String tag) {

	}

	@Override
	public void onSuccess(String response, String tag) {
		recyclerView.loadMoreComplete();
		recyclerView.refreshComplete();
		userPrefUtils.setMessNum(0);
		setLoadViewGONE();
		if (JSONHelper.isSuccess(response)) {
			TopicMessageData data= JsonUtil.getMode(response,TopicMessageData.class);
			if(null!=data&&null!=data.getData()&&data.getData().size()>0){
				if(currPage==1){
					topicMesses.clear();
				}
				currPage++;
				topicMesses.addAll(data.getData());
				messReplyAdapter.notifyDataSetChanged();
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put("event", BroadCastEvent.CHATLIST_NOMESS);
				if(topicMesses.size()>0)
					hashMap.put("obj", true);
				else
					hashMap.put("obj",false);
				hashMap.put("key",1);
				EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
						ThreadEnforcer.MAIN).post(hashMap);
				userPrefUtils.setMessNum(0);
				setTip();
			}else{
				recyclerView.noMoreLoading();
			}

		}
	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		recyclerView.setLoadingMoreEnabled(true);
		recyclerView.loadMoreComplete();
		recyclerView.refreshComplete();
		setNoNetWork(new ReLoadClickListener() {
			@Override
			public void reload() {
				getData(currPage);
			}
		});
		ResultCode.toastVolleyError(getActivity(), volleyError);
	}

	public void setTip(){
		try {
			final int num=userPrefUtils.getMessNum();
			if(num>0) {
                (getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        head_view.setVisibility(View.VISIBLE);
                        head_text.setText("你有"+num+"条新消息");
                        messReplyAdapter.notifyDataSetChanged();
                    }
                });

            }else{
                head_view.setVisibility(View.GONE);
                messReplyAdapter.notifyDataSetChanged();
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
